/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.blog.model.objectify;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import lt.ntec.danblog.server.blog.model.Post;
import lt.ntec.danblog.server.blog.model.PostDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Tadas
 */
class PostParentProxy implements InvocationHandler {

    private static final Logger LOG =
            LoggerFactory.getLogger(PostParentProxy.class);
    private Post post;
    private final BlogComment blogComment;
    private final PostDAO postDAO;

    public static Post newInstance(BlogComment blogComment,
                                                 PostDAO postDAO) {
        return (Post) Proxy.newProxyInstance(Post.class.
                getClassLoader(), new Class[]{Post.class}, new PostParentProxy(
                blogComment, postDAO));
    }

    private PostParentProxy(BlogComment blogComment, PostDAO postDAO) {
        this.blogComment = blogComment;
        this.postDAO = postDAO;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {

        if (post == null) {
            LOG.debug("Creating proxy");
            post = postDAO.getById(blogComment.getParentKey().
                    getId());
        }

        LOG.debug("Delegating call for " + method.getName());

        return method.invoke(post, args);
    }
}
